//lgs20160808
app.controller("examSubjectCtrl",function($scope,$state,$http,$ionicLoading,$ionicActionSheet){
    var QuestionOld=null;//加载历史用户答案
    var QuestionNew=null;//用户变更后的答案
    var QuestionNum=null;//试题序号
    var QuestionId=null;//试题ID
    var panDuanFlag=false;//判断题标记
    $scope.followShow = true;
    //上次作答保存在userAnswer中，最新作答保存在userAnswerNew中，每次提交前先比较，如果答案相同，无需保存。
    var userAnswer = [];
    var userAnswerNew = [];
    var user_info = JSON.parse(localStorage.getItem("UserInfo"));
    // var getPath = JSON.parse(localStorage.getItem("getPath"));
    angular.element(document).ready(function(){
        $scope.findQuestion();
    })



    //读取试题
    $scope.findQuestion = function (QuestionOrder) {
        //试题切换
        if(QuestionOrder == 'previous'){
            QuestionNum= QuestionNum - 1;
            if(QuestionNum != exam_subject.questionCnt){
                $scope.followShow = true;
            }
        }else if(QuestionOrder == 'follow'){
            QuestionNum= QuestionNum + 1;
            if(QuestionNum == exam_subject.questionCnt){
                $scope.followShow = false;
            }
        }else {
            QuestionNum=1;
        }
        if(QuestionNum == 0){
            $ionicLoading.show({
                template: "已经是第一道试题了！",
                duration: 3000
            });
        }else{
            var url = getPath.url+getPath.name+"/app/findQuestion";
            $http({
                url: url,
                method: "POST",
                headers:{'Content-Type':'application/x-www-form-urlencoded'},
                data: {
                    userId:user_info.userId ,
                    examCircle:exam_subject.examCode,
                    examOrder:QuestionNum
                }
            }).success(function (data) {
                    $scope.nQuestionCnt=data.nQuestionCnt;

                    data=data.examQuestionDTO;

                    if (data.examOrder != null) {
                        // $scope.examListData = data;
                        QuestionId=data.chooseAnswerList[0].questionId;
                        if (data.type=="0"){
                            panDuanFlag = false;
                            //清除上一次绑定的内容
                            $scope.chooseAnswerListCheckbox=null;
                            $scope.chooseAnswerListRadio=null;
                            //绑定数据
                            $scope.type='单选题';
                            // $scope.examOrder=data.examOrder;
                            // $scope.questionContent=data.questionContent;
                            for(i=0;i<data.chooseAnswerList.length;i++){
                                if((data.userAnswerList!=null)&&(data.userAnswerList.indexOf(data.chooseAnswerList[i].answerCode)!=-1)){
                                    data.chooseAnswerList[i].isTrue=1;
                                }else {
                                    data.chooseAnswerList[i].isTrue=0;
                                }
                            }
                            $scope.chooseAnswerListRadio=data.chooseAnswerList;
                            //获取上次用户答题答案
                            $scope.getOldAnswer(data.chooseAnswerList);
                        }else  if (data.type=="1"){
                            panDuanFlag = false;
                            //清除上一次绑定的内容
                            $scope.chooseAnswerListRadio=null;
                            $scope.chooseAnswerListCheckbox=null;
                            //绑定数据
                            $scope.type='多选题';
                            // $scope.examOrder=data.examOrder;
                            // $scope.questionContent=data.questionContent;
                            for(i=0;i<data.chooseAnswerList.length;i++){
                                if((data.userAnswerList!=null)&&(data.userAnswerList.indexOf(data.chooseAnswerList[i].answerCode)!=-1)){
                                    data.chooseAnswerList[i].isTrue=1;
                                }else {
                                    data.chooseAnswerList[i].isTrue=0;
                                }
                            }
                            $scope.chooseAnswerListCheckbox=data.chooseAnswerList;

                            //获取上次用户答题答案
                            $scope.getOldAnswer(data.chooseAnswerList);
                        }else  if (data.type=="2"){
                            panDuanFlag = true;
                            //清除上一次绑定的内容
                            $scope.chooseAnswerListCheckbox=null;

                            //绑定数据
                            $scope.type='判断题';
                            // $scope.examOrder=data.examOrder;
                            // $scope.questionContent=data.questionContent;
                            //判断题，判断上次答题结果
                            if (data.userAnswerList!=null){
                                if(data.userAnswerList.indexOf('0')!=-1){
                                    $scope.chooseAnswerListRadio=[{answerCode:"A",answerContent:"正确",isTrue:1},{answerCode:"B",answerContent:"错误",isTrue:0}]
                                    userAnswer[0]='A';
                                    userAnswerNew[0]='A';
                                }else if(data.userAnswerList.indexOf('1')!=-1){
                                    $scope.chooseAnswerListRadio=[{answerCode:"A",answerContent:"正确",isTrue:0},{answerCode:"B",answerContent:"错误",isTrue:1}]
                                    userAnswer[0]='B';
                                    userAnswerNew[0]='B';
                                }
                            }else {
                                $scope.chooseAnswerListRadio=[{answerCode:"A",answerContent:"正确",isTrue:0},{answerCode:"B",answerContent:"错误",isTrue:0}]
                            }
                            $scope.getOldAnswer(userAnswer);
                        }
                        $scope.examOrder=data.examOrder;
                        $scope.questionContent=data.questionContent;
                        // $scope.resolve=data.resolve;
                        // userAnswerNew = userAnswer;
                    } else {
                        QuestionNum= QuestionNum - 1;
                        // $ionicLoading.show({
                        //     template: "没有更多考试题！",
                        //     duration: 3000
                        // });
                    }
                })
                .error(function () {
                    $ionicLoading.hide();
                    $ionicLoading.show({
                        template: "获取数据失败，请联系管理员!",
                        duration: 3000
                    });
                });
        }


    }
    //读取历史答题记录
    $scope.getOldAnswer = function (chooseAnswerList) {
        for(i=0;i<chooseAnswerList.length;i++){
            if(chooseAnswerList[i].isTrue==1){
                userAnswer.push(chooseAnswerList[i].answerCode);
                userAnswerNew.push(chooseAnswerList[i].answerCode);
            }
        }
    }

    //记录用户单选及判断答案
    $scope.getUserRadioAnswer = function (answer) {
        userAnswerNew[0]=answer;
    }
    //记录用户多选答案
    $scope.getUserCheckbosAnswer = function ($event,answer) {
        var checkbox = $event.target;
        var action = (checkbox.checked?'add':'remove');

        //如果是勾选操作，且答案没被勾选
        if(action == 'add' && userAnswerNew.indexOf(answer) == -1){
            userAnswerNew.push(answer);
        }

        //如果是取消勾选，且答案已经被勾选
        if(action == 'remove' && userAnswerNew.indexOf(answer)!=-1){
            var idx = userAnswerNew.indexOf(answer);
            userAnswerNew.splice(idx,1);
        }
    }

    //试题切换并提交
    $scope.changeQuestion = function (QuestionOrder) {
        debugger
        QuestionOld='';
        QuestionNew='';
        //分别从userAnswer和userAnswerNew中提取
        for(i=0;i<userAnswer.length;i++){
            QuestionOld += userAnswer[i];
        }
        for(i=0;i<userAnswerNew.length;i++){
            QuestionNew += userAnswerNew[i];
        }
        //QuestionOld等于QuestionNew则不提交，否则提交答案
        if(QuestionOld==QuestionNew){
            userAnswer = [];
            userAnswerNew = [];
            // alert('答案相同不需要保存');
            $scope.findQuestion(QuestionOrder);
        }else {
            // alert('已提交');
            //提交保存
            $scope.saveExamUser(QuestionOrder);
        }
    }

    //提交保存
    $scope.saveExamUser = function (QuestionOrder) {
        // $state.go("home.examCatalogue");

        var userAnswerFinl=userAnswerNew[0];
        //如果是判断题，则进行内容转换，A转换成0，B转换成1；
        if( (panDuanFlag)&&(userAnswerFinl == 'A') ){
            userAnswerFinl='0';
        }else if( (panDuanFlag)&&(userAnswerFinl == 'B') ){
            userAnswerFinl='1';
        }

        for(i=1;i<userAnswerNew.length;i++){
            userAnswerFinl+=','+userAnswerNew[i];
        }
        var url = getPath.url+getPath.name+"/app/saveExamUser";
        $http({
            url: url,
            method: "POST",
            headers:{'Content-Type':'application/x-www-form-urlencoded'},
            data: {
                userId:user_info.userId ,
                questionId:QuestionId,
                examCircle:exam_subject.examCode,
                userAnswer:userAnswerFinl

            }
        }).success(function (data) {
            $scope.findQuestion(QuestionOrder);

            userAnswer = [];
            userAnswerNew = [];
        }).error(function () {
            $ionicLoading.hide();
            $ionicLoading.show({
                template: "该题已作答，请勿修改！",
                duration: 3000
            });
        });

    }

    //打开考试结束页面
    $scope.openExamAnalysis = function (answer) {
        $ionicActionSheet.show({
            buttons:[
                {text:"确定"},
                // {text:"从相册选择"}
            ],
            titleText:"结束后将无法再次答题！",
            cancelText:"取消",
            cancel:function(){

            },
            buttonClicked:function(index){
                $scope.changeQuestion('follow');
                $state.go("home.examAnalysis");
            }
        });


    }

});